package com.code.zjm.firstapp;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by ZJM on 2017/3/2.
 */

public class MainService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("Service OnBind");
        return serviceBinder;
    }


    //内部类对象，用于在activity中成功绑定服务
    public ServiceBinder serviceBinder = new ServiceBinder();

    public class ServiceBinder extends Binder {

        /**
         * 获取当前服务的对象
         *
         * @return
         */
        MainService getService() {
            return MainService.this;
        }
    }

    /**
     * 获取当前计时器的数字
     *
     * @return
     */
    public int getCurrentNum() {
        return i;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service onCreate");
        startTime();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service onDestroy");
        stopTimer();
    }

    private int i = 0;
    private Timer timer = null;
    private TimerTask task = null;

    public void startTime() {//开始计时
        if (timer == null) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    i++;
                    System.out.println(i);
                }
            };
            timer.schedule(task, 1000, 1000);
        }
    }

    public void stopTimer() {//停止
        if (timer != null) {
            task.cancel();
            timer.cancel();
            //对应启动Timer时的timer是null；
            task = null;
            timer = null;
        }
    }

}
